package cn.wy.user.service.impl;

import cn.wy.basic.dto.LoginDto;
import cn.wy.basic.jwt.JwtUtils;
import cn.wy.basic.jwt.LoginData;
import cn.wy.basic.jwt.RsaUtils;
import cn.wy.basic.util.AjaxResult;
import cn.wy.basic.util.HttpUtil;
import cn.wy.basic.util.Md5Utils;
import cn.wy.basic.util.StrUtils;
import cn.wy.exception.BusinessException;
import cn.wy.org.mapper.EmployeeMapper;
import cn.wy.system.domain.Menu;
import cn.wy.system.mapper.MenuMapper;
import cn.wy.system.mapper.PermissionMapper;
import cn.wy.user.constant.WxConstants;
import cn.wy.user.domain.Logininfo;
import cn.wy.user.domain.User;
import cn.wy.user.domain.Wxuser;
import cn.wy.user.mapper.LogininfoMapper;
import cn.wy.user.mapper.UserMapper;
import cn.wy.user.mapper.WxuserMapper;
import cn.wy.user.service.LogininfoService;
import cn.wy.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements LogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String checkPass = loginDto.getCheckPass();

        //一：校验 - 空值校验
        if(StringUtils.isEmpty(account) || StringUtils.isEmpty(checkPass)){
            throw new BusinessException("信息不能为空!!!");
        }
        //二：校验 - 账号校验
        Logininfo logininfo = logininfoMapper.findByAccount(loginDto);
        if(logininfo==null){
            throw new BusinessException("账号未注册!!!");
        }
        //三：校验 - 密码 - 加密加盐
        //前端输入的密码进行加密加盐
        String inputPwd = Md5Utils.encrypByMd5(checkPass + logininfo.getSalt());
        if(!inputPwd.equals(logininfo.getPassword())){
            throw new BusinessException("账号或密码错误!!!");
        }

        //四：校验 - 是否被禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("该账号被禁用，请联系管理员!!!");
        }

        //五：生成token，并将登录信息保存到redis数据库，设置30有效
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return map;
    }

    /**
     * 微信登录
     * @param code
     * @return
     */
    @Override
    public AjaxResult wechatLogin(String code) {
        //1.根据code发送第二个请求：httpUtil，返回json格式字符串
        //a.准备第二个请求和参数
        String url = WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID).replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);
        //调用工具类发送请求，返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        /*
        {
        "access_token":"ACCESS_TOKEN",
        "expires_in":7200,
        "refresh_token":"REFRESH_TOKEN",
        "openid":"OPENID",
        "scope":"SCOPE",
        "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
        }
         */

        //2.使用fastJson进行处理：获取token，openid
        JSONObject obj = JSONObject.parseObject(jsonStr);
        String accessToken = obj.getString("access_token");
        String openId = obj.getString("openid");

        //3.根据openid去查询t_wxuser表
        Wxuser wxuser = wxuserMapper.findByOpenid(openId);
        //3.1.查到了=以前扫过码 = 直接免密登陆【不需要在页面中输入用户名和密码就可以登陆】
        //如果通过openid查询到了微信用户对象
        if(wxuser!=null){
            //疑问：user_id可能为null吗？只要有wxuser，就一定会绑定user_id
            User user = userMapper.findOne(wxuser.getUserId());
            if(user!=null){ //并且关联的User对象也有值 - 绑定了 - 后续扫码 - 免密登陆
                Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());
                Map<String, Object> map = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setResultObj(map);
            }
        }
        String params = "?accessToken="+accessToken+"&openId="+openId;
        //3.2.如果没有查到 = 响应给前端token，openid，前端跳转到绑定页面
        return AjaxResult.me().setSuccess(false).setResultObj(params);
    }

    /**
     * 微信绑定业务
     * @param map
     * @return
     */
    @Override
    @Transactional
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //校验
        //1.校验 - 空置校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("数据不能为空");
        }

        //2.校验 - 验证码是否过期  //code:1215215155
        Object redisCode = redisTemplate.opsForValue().get("binder:" + phone);
        if(redisCode==null){
            throw new BusinessException("验证码过期");
        }
        //3.校验 - 验证码是否正确
        if(!redisCode.toString().split(":")[0].equalsIgnoreCase(verifyCode.trim())){
            throw new BusinessException("验证码错误");
        }


        //绑定用户：t_wxUser【user_id】 绑定 t_user
        //4.获取WxUser - 发送第三个请求 - json字符串
        String url = WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN",accessToken)
                .replace("OPENID",openId);

        String jsonStr = HttpUtil.httpGet(url);
        Wxuser wxuser = jsonStr2Wxuser(jsonStr); //user_id
        Wxuser dbWxuser = wxuserMapper.findByOpenid(openId);
        if(dbWxuser!=null){
            wxuserMapper.delete(dbWxuser.getId());
        }
        //5.通过phone查询User
        User user = userMapper.findOneByPhone(phone);
        //5.1.如果没有 - 根据phone创建User对象 - 创建Logininfo对象 - 保存Logininfo对象 - 保存User对象
        if(user == null){
            user = phone2User(phone);
            Logininfo logininfoTmp= user2Logininfo(user);

            logininfoMapper.insert(logininfoTmp);
            user.setLogininfoId(logininfoTmp.getId());
            userMapper.insert(user);
        }
        //6.将User对象的id设置到WxUser对象中
        wxuser.setUserId(user.getId());
        //7.将WxUser对象添加到数据库
        wxuserMapper.insert(wxuser);

        //8.做免密登录
        Logininfo logininfo = logininfoMapper.findOne(user.getLogininfoId());
        String token = UUID.randomUUID().toString();
        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setResultObj(resultMap);
    }
    Map<String,Object> map = new HashMap<>();
    //LogininfoServiceImpl实现类中
    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        try {
            //细节：如果是管理员才需要加四个数据，如果是用户只需要：登录信息对象，jwt串【1,4】
            //一：想办法获取四个数据
            //1.登录信息对象 - 在参数中
            logininfo.setPassword(null);
            logininfo.setSalt(null);
            map.put("logininfo",logininfo);
            LoginData loginData = new LoginData();
            loginData.setLogininfo(logininfo);
            if(logininfo.getType()==0){//后台管理员
                //2.当前登录人的所有权限的sn集合 - 昨天写过了 - 直接调用方法
                List<String> permissions = employeeMapper.getPermissionByLogininfoId(logininfo.getId());
                map.put("permissions",permissions);
                loginData.setPermissions(permissions);
                //3.当前登录人的所有二级菜单及其它的父级菜单【前端需要】 - 自己写 - 难点1
                List<Menu> menus = employeeMapper.getMenusByLogininfoId(logininfo.getId());
                map.put("menus",menus);
                loginData.setMenus(menus);
            }
            //4.将以上三个数据装到LoginData  - 使用工具类进行加密【1 2】 - jwt串
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30000);//没有做刷新过期时间

            //二：将四个数据装到map进行返回。疑问：jwt串里面不是已经有登录信息，权限和菜单了吗？ - 前端没有做解密
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  map;
    }
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机的纯数据密码
        String randomPwd = StrUtils.getRandomString(6);
        String md5Pwd = Md5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }
}
